package com.b2c.repository.tao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.tao.TaokeywordViewEntity;

@Repository
public class TaokeywordViewRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Integer addKeyword(Integer shopId, String keyword, String source, Long goodsId, Integer views, String date) {
        String sql = "INSERT INTO dc_tao_keyword_view_log (shopId,goodsId,keyword,source,views,date) VALUE (?,?,?,?,?,?) ";
        jdbcTemplate.update(sql, shopId, goodsId, keyword, source, views, date);
        return 1;
    }

    @Transactional
    public PagingResponse<TaokeywordViewEntity> getList(Integer shopId, Integer pageIndex, Integer pageSize,
            Long goodsId, String keyword,String date) {

        List<Object> params = new ArrayList<>();
        StringBuilder sb = new StringBuilder("SELECT SQL_CALC_FOUND_ROWS  tk.*,tg.title,tg.goodsNum,tg.goodsImg ");
        sb.append(" FROM dc_tao_keyword_view_log ").append(" as tk ");
        sb.append(" LEFT JOIN dc_tao_goods ").append(" as tg on tg.goodsId = tk.goodsId ");

        sb.append(" WHERE tk.shopId = ?  ");
        params.add(shopId);

        if (StringUtils.hasText(keyword)) {
            sb.append(" AND tk.keyword = ? ");
            params.add(keyword);
        }
        if (goodsId != null && goodsId > 0) {
            sb.append(" AND tk.goodsId = ? ");
            params.add(goodsId);
        }
        if (StringUtils.hasText(date)) {
            sb.append(" AND tk.date = ? ");
            params.add(date);
        }

        sb.append(" ORDER BY tk.date DESC ");

        sb.append("  LIMIT ?,?");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);

        var list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(TaokeywordViewEntity.class),
                params.toArray(new Object[params.size()]));

        int totalSize = getTotalSize();

        return new PagingResponse<>(pageIndex, pageSize, totalSize, list);
    }

    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }

}
